import React, { useState } from 'react';
import { Table } from 'antd';
import DragEditTable from '@/components/DragEditTable/index';

type EditableTableProps = Parameters<typeof Table>[0];

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}
const defaultColumns: (ColumnTypes[number] & {
  editable?: boolean;
  dataIndex: string;
})[] = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
    editable: true,
  },
  {
    title: 'Age',
    dataIndex: 'age',
    key: 'age',
    editable: true,
  },
  {
    title: 'Address',
    dataIndex: 'address',
    key: 'address',
    editable: true,
  },
];

const App: React.FC = () => {
  const [data, setData] = useState([
    {
      key: '1',
      name: 'John Brown',
      age: 32,
      address: 'New York No. 1 Lake Park',
    },
    {
      key: '2',
      name: 'Jim Green',
      age: 42,
      address: 'London No. 1 Lake Park',
    },
    {
      key: '2-1',
      name: 'Jim Green-1',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '2',
    },
    {
      key: '2-2',
      name: 'Jim Green-2',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '2',
    },
    {
      key: '3',
      name: 'Tom Black',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
    },
    {
      key: '3-1',
      name: 'Tom Black-1',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '3',
    },
    {
      key: '3-2',
      name: 'Tom Black-2',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '3',
    },
    {
      key: '3-3',
      name: 'Tom Black-3',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '3',
    },
    {
      key: '3-3-1',
      name: 'Tom Black-3-1',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '3-3',
    },
    {
      key: '3-3-2',
      name: 'Tom Black-3-2',
      age: 32,
      address: 'Sidney No. 1 Lake Park',
      pid: '3-3',
    },
  ]);

  const handleSave = (row: DataType) => {
    const newData = [...data];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setData(newData);
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  return <DragEditTable columns={columns as ColumnTypes} dataSource={data} />;
};

export default App;
